package com.chatbot.service;

import com.chatbot.config.DashScopeConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class QwenApiService {

    private static final String QWEN_API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String MODEL = "qwen-plus-character";

    @Autowired
    private DashScopeConfig dashScopeConfig;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String generateResponse(String characterPrompt, String conversationHistory, String userMessage) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + dashScopeConfig.getApiKey());

            // 构建输入提示
            String prompt = buildPrompt(characterPrompt, conversationHistory, userMessage);

            // 构建请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", MODEL);
            
            ObjectNode input = requestBody.putObject("input");
            input.put("prompt", prompt);

            ObjectNode parameters = requestBody.putObject("parameters");
            parameters.put("temperature", 0.8);
            parameters.put("top_p", 0.8);
            parameters.put("result_format", "text");
            parameters.put("max_tokens", 1500);

            // 发送请求
            HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);
            String response = restTemplate.postForObject(QWEN_API_URL, request, String.class);

            // 解析响应
            JsonNode responseJson = objectMapper.readTree(response);
            return responseJson.path("output").path("text").asText();

        } catch (Exception e) {
            throw new RuntimeException("调用千问API失败: " + e.getMessage());
        }
    }

    private String buildPrompt(String characterPrompt, String conversationHistory, String userMessage) {
        StringBuilder prompt = new StringBuilder();
        
        // 添加角色设定
        prompt.append("你现在要扮演一个角色，请严格按照以下设定进行角色扮演：\n\n");
        prompt.append(characterPrompt).append("\n\n");
        
        // 添加对话历史
        if (conversationHistory != null && !conversationHistory.isEmpty()) {
            prompt.append("以下是之前的对话历史：\n");
            prompt.append(conversationHistory).append("\n\n");
        }
        
        // 添加系统指令
        prompt.append("请记住：\n");
        prompt.append("1. 你必须始终保持角色设定中的性格和说话方式\n");
        prompt.append("2. 回复要符合角色的背景和经历\n");
        prompt.append("3. 可以适当加入表情和动作描写，但要符合角色特点\n");
        prompt.append("4. 禁止讨论或提及敏感话题\n");
        prompt.append("5. 回复要自然、流畅，像真实对话一样\n\n");
        
        // 添加用户消息
        prompt.append("用户：").append(userMessage).append("\n");
        prompt.append("角色：");
        
        return prompt.toString();
    }
} 